package com.zmzncs.lmtc.common.interactive.miwang;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.zmzncs.lmtc.common.pojo.miwang.*;
import com.zmzncs.lmtc.common.util.GeoHashUtil;
import com.zmzncs.lmtc.common.util.JsonUtil;
import com.zmzncs.lmtc.common.util.JwtUtil;
import com.zmzncs.lmtc.common.util.SnowflakeIdUtil;
import com.zmzncs.lmtc.module.park.dao.ParkEntranceDao;
import com.zmzncs.lmtc.module.park.dao.ParkInfoDao;
import com.zmzncs.lmtc.module.park.pojo.park_entrance.ParkEntrance;
import com.zmzncs.lmtc.module.park.pojo.park_entrance.ParkEntranceDTO;
import com.zmzncs.lmtc.module.park.pojo.park_info.ParkInfo;
import com.zmzncs.lmtc.module.park.pojo.park_info.ParkInfoDTO;
import com.zmzncs.lmtc.module.promotion.pojo.month_rule.MonthRule;
import com.zmzncs.lmtc.module.promotion.pojo.month_rule_fee_scale.MonthRuleFeeScale;
import com.zmzncs.lmtc.module.promotion.pojo.month_rule_park.MonthRulePark;
import com.zmzncs.lmtc.module.promotion.service.MonthRuleFeeScaleService;
import com.zmzncs.lmtc.module.promotion.service.MonthRuleParkService;
import com.zmzncs.lmtc.module.promotion.service.MonthRuleService;
import com.zmzncs.lmtc.module.system.pojo.user.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * 咪网云盒获取数据信息
 *
 * @Author 高博文
 * @Date 2020/11/19 15:18
 */
@Slf4j
@Component
public class MWPullData {

    @Autowired
    ParkInfoDao parkInfoDao;
    @Autowired
    ParkEntranceDao parkEntranceDao;
    @Autowired
    MonthRuleService monthRuleService;
    @Autowired
    MonthRuleParkService monthRuleParkService;
    @Autowired
    MonthRuleFeeScaleService monthRuleFeeScaleService;

    @Autowired
    HttpServletRequest request;

    //  泊链分配的厂商编号
    public static String unionId;
    @Value("${bolian.userUnionId}")
    public void setUnionId(String unionId) {
        this.unionId = unionId;
    }

    /**
     * 包月车充值续费
     */
    public String insertOrRenewFixedCar(MWFixedCarSyncMode mode) {
        String dataStr = MiWangParkOpenapi.mwpark_sandbox_insertOrRenewFixedCarHttpSyncTest(mode);
        JsonNode node = JsonUtil.getJsonNode(dataStr);
        String code = JsonUtil.getJsonValue(node, "code");
        if (StringUtils.isNotBlank(code) && code.equals("200")) {
            return "包月车充值续费成功";
        }
        return null;
    }

    /**
     * 获取咪网停车场信息
     */
    public ParkInfoDTO getMWPark(String partnerCode) {

        String dataStr = MiWangParkOpenapi.mwpark_sandbox_getParkingLotByCodeHttpSync(partnerCode);
        JsonNode node = JsonUtil.getJsonNode(dataStr);
        String code = JsonUtil.getJsonValue(node, "code");

        if (StringUtils.isNotBlank(code) && code.equals("200")) {
            String data = JsonUtil.getJsonValue(node, "data");
            log.info("查询停车场信息：" + data);
            MWParkingLotRes mwParkingLotRes = JsonUtil.JSONToObj(data, MWParkingLotRes.class);

            ParkInfoDTO parkInfoDTO = new ParkInfoDTO();
            parkInfoDTO.setParkName(mwParkingLotRes.getParkingLotName());
            parkInfoDTO.setParkAddress(mwParkingLotRes.getParkingLotAddress());
            parkInfoDTO.setPartnerCode(partnerCode);
            parkInfoDTO.setTelephone(mwParkingLotRes.getContactMobile());
            parkInfoDTO.setLongitude(mwParkingLotRes.getLongitude());
            parkInfoDTO.setLatitude(mwParkingLotRes.getLatitude());
            parkInfoDTO.setPriceDesc("暂无收费规则");
            parkInfoDTO.setTotalParkSpace(mwParkingLotRes.getTotalFixedCount());
            parkInfoDTO.setEmptyParkSpace(mwParkingLotRes.getLeftFixedCount());
            parkInfoDTO.setUpdateFromBolian(0);
            parkInfoDTO.setIsShow(1);
            parkInfoDTO.setBolianParkId(mwParkingLotRes.getParkingLotCode());
            parkInfoDTO.setBolianParkUnionId(unionId);
            parkInfoDTO.setParkSource(2);

            String geoHashBinary = GeoHashUtil.getBinary(Double.parseDouble(parkInfoDTO.getLongitude()), Double.parseDouble(parkInfoDTO.getLatitude()), 32);
            parkInfoDTO.setGeohash(GeoHashUtil.getBase32(geoHashBinary));

            ParkInfoDTO parkInfo = parkInfoDao.getParkByBolianParkId(mwParkingLotRes.getParkingLotCode());
            if (parkInfo == null) {
                Long parkSnowflakeId = new SnowflakeIdUtil(new Random().nextInt(9), new Random().nextInt(9)).nextId();
                parkInfoDTO.setId(parkSnowflakeId);
                parkInfoDTO.setCreateTime(new Date());

                ParkInfo park = new ParkInfo();
                BeanUtils.copyProperties(parkInfoDTO,park);
                parkInfoDao.insert(park);
            } else {
                parkInfoDTO.setId(parkInfo.getId());
                ParkInfo park = new ParkInfo();
                BeanUtils.copyProperties(parkInfoDTO,park);
                parkInfoDao.updateById(park);
            }
            return parkInfoDTO;
        }
        return null;
    }


    /**
     * 获取停车场通道道闸
     */
    public void getMWEntranceAndRoadWay(String partnerCode, String bolianParkId) {
        String dataEntranceAndRoadWayStr = MiWangParkOpenapi.mwpark_sandbox_queryEntranceAndRoadWayHttpSync(partnerCode);
        JsonNode nodeEntranceAndRoadWay = JsonUtil.getJsonNode(dataEntranceAndRoadWayStr);
        String codeEntranceAndRoadWay = JsonUtil.getJsonValue(nodeEntranceAndRoadWay, "code");

        if (StringUtils.isNotBlank(codeEntranceAndRoadWay) && codeEntranceAndRoadWay.equals("200")) {
            String dateEntranceAndRoadWay = JsonUtil.getJsonValue(nodeEntranceAndRoadWay, "data");

            List<MWEntranceAndRoadWayRes> mwList = JSONArray.parseArray(dateEntranceAndRoadWay, MWEntranceAndRoadWayRes.class);
            if (mwList != null && !mwList.isEmpty()) {
                for (MWEntranceAndRoadWayRes mwEntrance : mwList) {
                    ParkEntrance parkEntrance = new ParkEntrance();

                    parkEntrance.setEntranceName(mwEntrance.getEntranceName());
                    parkEntrance.setEntranceCode(mwEntrance.getEntranceCode());
                    parkEntrance.setEntranceType(mwEntrance.getEntranceType());

                    List<MWEntranceAndRoadWayRes.RoadWay> roadWays = mwEntrance.getRoadWayDtoList();
                    for (MWEntranceAndRoadWayRes.RoadWay roadWay : roadWays) {
                        Long parkEntranceId = new SnowflakeIdUtil(new Random().nextInt(9), new Random().nextInt(9)).nextId();
                        parkEntrance.setId(parkEntranceId);
                        parkEntrance.setRoadWayName(roadWay.getRoadWayName());
                        parkEntrance.setRoadWayCode(roadWay.getRoadWayCode());
                        parkEntrance.setRoadWayType(roadWay.getRoadWayType());

                        ParkInfoDTO parkInfo = parkInfoDao.getParkByBolianParkId(bolianParkId);
                        //查询停车场道闸信息
                        List<ParkEntranceDTO> entranceList = parkEntranceDao.getEntranceList(mwEntrance.getEntranceCode(), roadWay.getRoadWayCode());
                        if (parkInfo != null && (entranceList == null || entranceList.isEmpty())) {
                            parkEntrance.setParkId(parkInfo.getId());
                            parkEntranceDao.insert(parkEntrance);
                        }
                    }
                }
            }
        }
    }

    /**
     * 获取咪网月租车分组信息
     */
    @Transactional
    public void getMWMonthRule(String partnerCode) {
        UserLoginVO loginUser = JwtUtil.getLoginUser(request);

        String dataStr = MiWangParkOpenapi.mwpark_sandbox_queryFixedCarRuleHttpSync(partnerCode);
        JsonNode node = JsonUtil.getJsonNode(dataStr);
        String code = JsonUtil.getJsonValue(node, "code");

        if (StringUtils.isNotBlank(code) && code.equals("200")) {
            String data = JsonUtil.getJsonValue(node, "data");
            log.info("查询停车场包月车分组：" + data);

            List<MWFixedCarRule> ruleList = JSONArray.parseArray(data, MWFixedCarRule.class);
            if (ruleList != null && !ruleList.isEmpty()) {

                /**根据泊链停车场Id查询停车场信息 */
                ParkInfoDTO parkInfo = parkInfoDao.getParkByBolianParkId(ruleList.get(0).getParkingLotCode());
                if (parkInfo != null) {

                    String ruleName = parkInfo.getParkName() + "月租规则";
                    LambdaUpdateWrapper<MonthRule> monthRuleWrapper = new LambdaUpdateWrapper();
                    monthRuleWrapper.eq(MonthRule::getRuleName, ruleName);
                    MonthRule monthRule = monthRuleService.getOne(monthRuleWrapper);

                    //添加更新月租卡规则信息
                    MonthRule month = new MonthRule();
                    month.setRuleName(ruleName);
                    if (monthRule == null) {
                        Long monthId = new SnowflakeIdUtil(new Random().nextInt(9), new Random().nextInt(9)).nextId();
                        month.setId(monthId);
                        int status = 0;
                        if(ruleList.size() == 1){
                            status = 1;
                        }
                        month.setStatus(status);
                        month.setCreateUserId(loginUser.getUserId());
                        monthRuleService.save(month);
                    } else {
                        if(ruleList.size() == 1){
                            month.setStatus(1);
                        }
                        month.setId(monthRule.getId());
                        monthRuleService.updateById(month);
                    }

                    LambdaUpdateWrapper<MonthRulePark> monthRuleParkWrapper = new LambdaUpdateWrapper<>();
                    monthRuleParkWrapper.eq(MonthRulePark::getMonthRuleId, month.getId())
                            .eq(MonthRulePark::getParkId, parkInfo.getId());
                    MonthRulePark monthRulePark = monthRuleParkService.getOne(monthRuleParkWrapper);

                    //添加更新月租卡适用停车场信息
                    MonthRulePark rulePark = new MonthRulePark();
                    rulePark.setMonthRuleId(month.getId());
                    rulePark.setParkId(parkInfo.getId());
                    if (monthRulePark == null) {
                        monthRuleParkService.save(rulePark);
                    } else {
                        rulePark.setId(monthRulePark.getId());
                        monthRuleParkService.updateById(rulePark);
                    }

                    for (MWFixedCarRule carRule : ruleList) {
                        LambdaUpdateWrapper<MonthRuleFeeScale> monthRuleFeeScaleWrapper = new LambdaUpdateWrapper<>();
                        monthRuleFeeScaleWrapper.eq(MonthRuleFeeScale::getMonthRuleId, month.getId());
                        List<MonthRuleFeeScale> monthRuleFeeScaleList = monthRuleFeeScaleService.list(monthRuleFeeScaleWrapper);

                        //添加月租卡月租卡支付方式信息
                        MonthRuleFeeScale feeScale = new MonthRuleFeeScale();
                        feeScale.setMonthRuleId(month.getId());
                        feeScale.setMonthRentType(1);
                        feeScale.setAmount(new BigDecimal(300));
                        feeScale.setMonthRentName(carRule.getFixedCarGroupName());

                        String ruleData = carRule.getData();
                        if (ruleData != null && !ruleData.equals("")) {
                            if (carRule.getFixedCarRuleType() != 4) {
                                String ruleInfo = mwParkRuleGroupInfo(ruleData);
                                feeScale.setRemark(ruleInfo);
                            }
                        }
                        if (monthRuleFeeScaleList == null || monthRuleFeeScaleList.isEmpty()) {
                            monthRuleFeeScaleService.save(feeScale);
                        } else {
//                            for (MonthRuleFeeScale ruleFeeScale : monthRuleFeeScaleList) {
//                                feeScale.setId(monthRuleFeeScaleList.getId());
//                                monthRuleFeeScaleService.updateById(feeScale);
//                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 解析咪网月租车分组分组免费时段详细说明
     */
    public String mwParkRuleGroupInfo(String data) {
        String ruleInfo = StringEscapeUtils.unescapeJava(data);
        MWFixedCarRuleData ruleData = JSON.parseObject(ruleInfo, MWFixedCarRuleData.class);

        StringBuffer dataStr = new StringBuffer();
        //周一
        List<MWFixedCarRuleData.FixedCarRuleData> monFreeTimes = ruleData.getMonFreeTimes();
        if (monFreeTimes != null && !monFreeTimes.isEmpty()) {
            dataStr.append("周一免费时段：");
            for (MWFixedCarRuleData.FixedCarRuleData freeTime : monFreeTimes) {
                String startTime = freeTime.getBlockStartTime();
                String endTime = freeTime.getBlockEndTime();
                dataStr.append(startTime + "-" + endTime + ",");
            }
        }
        //周二
        List<MWFixedCarRuleData.FixedCarRuleData> tueFreeTimes = ruleData.getTueFreeTimes();
        if (tueFreeTimes != null && !tueFreeTimes.isEmpty()) {
            dataStr.append(" 周二免费时段：");
            for (MWFixedCarRuleData.FixedCarRuleData freeTime : tueFreeTimes) {
                String startTime = freeTime.getBlockStartTime();
                String endTime = freeTime.getBlockEndTime();
                dataStr.append(startTime + "-" + endTime + ",");
            }
        }
        //周三
        List<MWFixedCarRuleData.FixedCarRuleData> wedFreeTimes = ruleData.getWedFreeTimes();
        if (wedFreeTimes != null && !wedFreeTimes.isEmpty()) {
            dataStr.append(" 周三免费时段：");
            for (MWFixedCarRuleData.FixedCarRuleData freeTime : wedFreeTimes) {
                String startTime = freeTime.getBlockStartTime();
                String endTime = freeTime.getBlockEndTime();
                dataStr.append(startTime + "-" + endTime + ",");
            }
        }
        //周四
        List<MWFixedCarRuleData.FixedCarRuleData> thursFreeTimes = ruleData.getThursFreeTimes();
        if (thursFreeTimes != null && !thursFreeTimes.isEmpty()) {
            dataStr.append(" 周四免费时段：");
            for (MWFixedCarRuleData.FixedCarRuleData freeTime : thursFreeTimes) {
                String startTime = freeTime.getBlockStartTime();
                String endTime = freeTime.getBlockEndTime();
                dataStr.append(startTime + "-" + endTime + ",");
            }
        }
        //周五
        List<MWFixedCarRuleData.FixedCarRuleData> friFreeTimes = ruleData.getFriFreeTimes();
        if (friFreeTimes != null && !friFreeTimes.isEmpty()) {
            dataStr.append(" 周五免费时段：");
            for (MWFixedCarRuleData.FixedCarRuleData freeTime : friFreeTimes) {
                String startTime = freeTime.getBlockStartTime();
                String endTime = freeTime.getBlockEndTime();
                dataStr.append(startTime + "-" + endTime + ",");
            }
        }
        //周六
        List<MWFixedCarRuleData.FixedCarRuleData> satFreeTimes = ruleData.getSatFreeTimes();
        if (satFreeTimes != null && !satFreeTimes.isEmpty()) {
            dataStr.append(" 周六免费时段：");
            for (MWFixedCarRuleData.FixedCarRuleData freeTime : satFreeTimes) {
                String startTime = freeTime.getBlockStartTime();
                String endTime = freeTime.getBlockEndTime();
                dataStr.append(startTime + "-" + endTime + ",");
            }
        }
        //周日
        List<MWFixedCarRuleData.FixedCarRuleData> sunFreeTimes = ruleData.getSunFreeTimes();
        if (sunFreeTimes != null && !sunFreeTimes.isEmpty()) {
            dataStr.append(" 周日免费时段：");
            for (MWFixedCarRuleData.FixedCarRuleData freeTime : sunFreeTimes) {
                String startTime = freeTime.getBlockStartTime();
                String endTime = freeTime.getBlockEndTime();
                dataStr.append(startTime + "-" + endTime + ",");
            }
        }
        return dataStr.toString();
    }

}


